package com.org.xiaosheng.cofig;

import com.mchange.v2.c3p0.ComboPooledDataSource;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;
import java.beans.PropertyVetoException;

/**
 * @author XiaoSheng
 * @date 2023-09-14
 * @dec 描述
 */
@Configuration
@EnableConfigurationProperties(C3p0DataSourceProperties.class)
public class C3p0DatasourceAutoConfigure {

    @Autowired
    private C3p0DataSourceProperties dataSourceProperties;

    /**
     * 提供基于c3p0配置的DataSource实例
     * @return
     */
    @Bean
    public DataSource c3p0DataSource() {
        // 连接池
        ComboPooledDataSource dataSource = new ComboPooledDataSource();
        try {
            dataSource.setDriverClass(dataSourceProperties.getDriverClassName());
            dataSource.setJdbcUrl(dataSourceProperties.getUrl());
            dataSource.setUser(dataSourceProperties.getUsername());
            dataSource.setPassword(dataSourceProperties.getPassword());
            return dataSource;
        } catch (PropertyVetoException e) {
            e.printStackTrace();
            new RuntimeException(e.getMessage());
            return null;
        }
    }

}
